﻿using VPLink2013.Framework;
using VPLink2013.Framework.Constants;
using VPLink2013.Framework.Extensions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using Microsoft.SharePoint.Publishing;
using System.Data.SqlClient;

namespace VPLink2013.Webcontrols
{
    public class WebcontrolVPLink : WebControl
    {
        protected string Template = string.Empty;
        protected string pathVP;
        protected string pathTemp;
        protected string pathCache;
        protected string connectionString;
        protected StringBuilder sbHtml = new StringBuilder();
        protected string urlPageCrt = string.Empty;

        protected bool isDefaultPage = false;
        protected string siteUrl = string.Empty;

        protected string encartPersoVersion = "VPLink2013";
        protected string rechercheVersion = "VPLink2013";
        protected bool widgetVisible = false;
        protected string photoEncartPerso = "Non";
        protected string logoMercure = "Non";
        protected Utilisateur UtilisateurCrt;
        protected string strFileCacheUtilisateur = string.Empty;

        private void SetConfigValues()
        {
            try
            {
                Dictionary<string, string> configDictionary = new Dictionary<string, string>()
                { 
                    { Fields.ConfigRechercheKeyName , rechercheVersion},
                    { Fields.ConfigEncartPersoKeyName, encartPersoVersion},
                    { Fields.ConfigLogoMercureKeyName, logoMercure},
                    { Fields.ConfigSiteUrlKeyName, siteUrl},
                    { Fields.ConfigConnectionStringKeyName, connectionString},
                    { Fields.ConfigVPLayoutsPathKeyName, pathVP}
                    //{ "LogoHeader",logoHeader},
                    //{ "DefaultPage",defaultPage},
                    //{ "Logo",logo},
                    //{ "PathTemp",pathTemp},
                    //{ "PathCache",pathCache}
                };
                getConfigValues(configDictionary);
                
                string _pathVP = configDictionary[Fields.ConfigVPLayoutsPathKeyName];

                pathVP = SPUtility.GetVersionedGenericSetupPath(_pathVP, 15);

                pathTemp = SPUtility.GetVersionedGenericSetupPath(Path.Combine(@_pathVP, @"Temp"), 15);

                pathCache = SPUtility.GetVersionedGenericSetupPath(Path.Combine(@_pathVP, @"_Cache" ), 15);

                this.Page.Cache.Insert(Fields.ConfigVPLayoutsPathKeyName, pathVP);
                this.Page.Cache.Insert("pathTemp", pathTemp);
                this.Page.Cache.Insert("pathCache", pathCache);
            }
            catch (Exception ex)
            {
                ContextTrace.AddTrace("Exception Lors de la recherche de la version VPLink");
                ContextTrace.AddTrace(ex.StackTrace);
            }
        }

        protected string getDefaultPageValue()
        {
            string defaultPage = string.Empty;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        if (PublishingWeb.IsPublishingWeb(web))
                        {
                            if (PublishingWeb.GetPublishingWeb(web).DefaultPage != null)
                            {
                                defaultPage = PublishingWeb.GetPublishingWeb(web).DefaultPage.ServerRelativeUrl;
                            }
                            else
                            {
                                defaultPage = web.RootFolder.WelcomePage;
                            }
                        }
                        else
                        {
                            defaultPage = web.RootFolder.WelcomePage;
                        }
                    }
                }
            });
            return defaultPage;
        }

        private void getConfigValues(Dictionary<string, string> configDictionary)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        SPList lstConfig = web.Lists.TryGetList(ListTitles.ConfigurationVPTitle);
                        if (lstConfig != null)
                        {
                            string strValeur = string.Empty;
                            SPListItemCollection coll = lstConfig.GetSPListItemCollectionWithTextFields(new List<string>() 
                                                        { Fields.ConfigKeyField, 
                                                            Fields.ConfigValueField });
                            if (coll != null)
                            {
                                foreach (string key in configDictionary.Keys.ToList())
                                {
                                    SPListItem item = coll.Cast<SPListItem>()
                                        .Where(x => x.GetItemListFieldValueAsText(Fields.ConfigKeyField).Equals(key, StringComparison.CurrentCultureIgnoreCase))
                                        .FirstOrDefault();
                                    if (item != null)
                                    {
                                        strValeur = item.GetItemListFieldValueAsHtml(Fields.ConfigValueField);
                                        configDictionary[key] = strValeur;
                                        this.Page.Cache.Insert(key, strValeur);
                                    }
                                }
                            }
                        }
                    }
                }
            });
        }

        protected override void OnLoad(EventArgs e)
        {
            if (this.Page.Cache.Get("configValuesInserted") != null)
            {
                CopyConfigParamsFromCache();
            }
            else
            {
                SetConfigValues();
                CopyConfigParamsFromCache();
            }
            isDefaultPage = SPContext.Current.ContextPageInfo != null
                ? SPContext.Current.ContextPageInfo.IsWebWelcomePage : false;
            base.OnLoad(e);
        }

        private void CopyConfigParamsFromCache()
        {
            rechercheVersion = (string)this.Page.Cache.Get(Fields.ConfigRechercheKeyName);
            encartPersoVersion = (string)this.Page.Cache.Get(Fields.ConfigEncartPersoKeyName);
            logoMercure = (string)this.Page.Cache.Get(Fields.ConfigLogoMercureKeyName);
            siteUrl = (string)this.Page.Cache.Get(Fields.ConfigSiteUrlKeyName);
            pathVP = (string)this.Page.Cache.Get(Fields.ConfigVPLayoutsPathKeyName);
            pathTemp = (string)this.Page.Cache.Get("pathTemp");
            pathCache = (string)this.Page.Cache.Get("pathCache");
            connectionString = (string)this.Page.Cache.Get(Fields.ConfigConnectionStringKeyName);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            string CurrentUserTrace = VPLink2013XsltTransformHelper.StringAfter(this.Context.User.Identity.Name);
            try
            {
                string strHtml = sbHtml.ToString();
                if (string.IsNullOrEmpty(strHtml))
                {
                    strHtml = string.Empty;
                    ContextTrace.AddTrace("UserControl vide : " + Template);
                }

                DateTime dtDateDebutProcess = DateTime.Now;
                Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR", false);

                writer.Write(strHtml);
                SaveHtmlTrace(strHtml);

                ContextTrace.AddTrace("-- Template : " + Template);
            }
            catch (System.Exception ex)
            {
                ContextTrace.AddTrace("Exception rendu " + ex.StackTrace);
            }
            ContextTrace.Save(Path.Combine(pathTemp, CurrentUserTrace), Template);
        }

        protected void SetUrlPageCrt()
        {
            Uri currentWebUri = new Uri(SPContext.Current.Web.Url);
            if (!string.IsNullOrEmpty(siteUrl))
            {
                Uri siteUri = new Uri(siteUrl);
                if(Uri.Compare(currentWebUri, siteUri, UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped, StringComparison.CurrentCultureIgnoreCase) == 0)
                {
                    urlPageCrt = new Uri(currentWebUri, this.Context.Request.Url.AbsolutePath).ToString();
                }
                else
                {
                    urlPageCrt = new Uri(siteUri, this.Context.Request.Url.AbsolutePath).ToString();
                }
            }
            else
            {
                urlPageCrt = new Uri(currentWebUri, this.Context.Request.Url.AbsolutePath).ToString();
            }
            urlPageCrt = urlPageCrt.ToLower();

        }

        protected string ParamFrm(string Name)
        {
            HttpRequest Request = Context.Request;
            string strValue;
            if (Request.Form.Count == 0)
            {
                strValue = Request.QueryString[Name];
            }
            else
            {
                strValue = Request.Form[Name];
                if (strValue == null || strValue == "undefined")
                {
                    strValue = Request.QueryString[Name];
                }
            }
            if (strValue == null || strValue == "undefined")
            {
                strValue = string.Empty;
            }
            strValue = strValue.Trim();
            if (strValue == "")
            {
                strValue = Request.QueryString[Name];
                if (strValue == null || strValue == "undefined")
                {
                    strValue = string.Empty;
                }
                strValue = strValue.Trim();
            }
            return strValue;
        }


        DateTime dtTrace = DateTime.Now;

        protected void SaveHtmlTrace(string strHtml)
        {
            try
            {
                string strFile = pathTemp + @"\" + Template + ".htm";
                System.IO.File.WriteAllText(strFile, strHtml);
            }
            catch (System.Exception)
            {
            }
        }
     
        protected void SetUtilisateurCrt()
        {
            UtilisateurCrt = FileSerialization.CreateObjFromXML<Utilisateur>(strFileCacheUtilisateur);
            if (UtilisateurCrt == null)
            {
                UtilisateurCrt = new Utilisateur();
                UtilisateurCrt.Login = this.Context.User.Identity.Name;
                ContextTrace.AddTrace("UtilisateurCrt.Login : " + UtilisateurCrt.Login);
                if (UtilisateurCrt.Login.ToLower() == @"oredis-vp\clrstrm-admmoss"
                    || UtilisateurCrt.Login.ToLower() == @"oredis-vp\mpbonazzi")
                {
                    UtilisateurCrt.IsDRH = "1";
                }
                else
                {
                    UtilisateurCrt.IsDRH = "0";
                }
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate() {
                        string strSql = @"SELECT Email 
                                            ,IsManager
                                            , IsInterimManager
                                            , IsJedi
                                            , IsCommercialVoyage, IsProductionVoyage
                                            , Site, Pays, Direction, Departement, Service 
                                            FROM Users WHERE LoginUser = '" + UtilisateurCrt.Login + "'";
                        ContextTrace.AddTrace("strSql : " + strSql);
                        if (!string.IsNullOrEmpty(connectionString))
                        {
                            SqlConnection conn = VPLink2013SqlHelper.GetConnection(connectionString);
                            ContextTrace.AddTrace(string.Format("Connection String 1 : {0}", connectionString));
                            if (conn != null)
                            {
                                SqlCommand command = VPLink2013SqlHelper.GetCommand(conn, strSql);
                                if (command != null)
                                {
                                    SqlDataReader Reader = command.ExecuteReader();
                                    if (Reader.Read())
                                    {
                                        UtilisateurCrt.Email = VPLink2013SqlHelper.GetValueReader(Reader, 0);
                                        UtilisateurCrt.Direction = VPLink2013SqlHelper.GetValueReader(Reader, 8);
                                        UtilisateurCrt.Departement = VPLink2013SqlHelper.GetValueReader(Reader, 9);
                                        UtilisateurCrt.Service = VPLink2013SqlHelper.GetValueReader(Reader, 10);
                                        UtilisateurCrt.IsInterne = "1";
                                        if (UtilisateurCrt.Email.IndexOf("prestataire") > 0)
                                        {
                                            UtilisateurCrt.IsInterne = "0";
                                        }
                                        if (VPLink2013SqlHelper.GetValueReaderBit(Reader, 1))
                                        {
                                            UtilisateurCrt.IsManager = "1";
                                        }
                                        else
                                        {
                                            if (VPLink2013SqlHelper.GetValueReaderBit(Reader, 2))
                                            {
                                                UtilisateurCrt.IsManager = "1";
                                            }
                                        }
                                        if (VPLink2013SqlHelper.GetValueReaderBit(Reader, 2))
                                        {
                                            UtilisateurCrt.IsInterimManager = "1";
                                        }
                                        if (VPLink2013SqlHelper.GetValueReaderBit(Reader, 3))
                                        {
                                            UtilisateurCrt.IsJedi = "1";
                                        }
                                        string strSite = VPLink2013SqlHelper.GetValueReader(Reader, 6);
                                        if (strSite.ToLower().Contains("plaine"))
                                        {
                                            UtilisateurCrt.IsLaPlaine = "1";
                                        }
                                        if (VPLink2013SqlHelper.GetValueReaderBit(Reader, 4) || VPLink2013SqlHelper.GetValueReaderBit(Reader, 5))
                                        {
                                            UtilisateurCrt.IsVoyage = "1";
                                        }
                                        UtilisateurCrt.Pays = VPLink2013SqlHelper.GetValueReader(Reader, 7);
                                    }
                                    VPLink2013SqlHelper.CloseReader(conn, Reader);
                                }
                                ContextTrace.AddTrace("UtilisateurCrt.Email : " + UtilisateurCrt.Email);
                                ContextTrace.AddTrace("UtilisateurCrt.IsInterne : " + UtilisateurCrt.IsInterne);
                                ContextTrace.AddTrace("UtilisateurCrt.IsManager : " + UtilisateurCrt.IsManager);
                            }
                        }
                    });
                }
                catch (Exception ex)
                {
                    ContextTrace.AddTrace("exception lors de la création utilisateur " + ex.Message);
                    ContextTrace.AddTrace(ex.StackTrace);
                }
                FileSerialization.CreateXmlFromObj(UtilisateurCrt, strFileCacheUtilisateur);
            }
        }
    }
}
